/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ita.escolaita.ejb;

import br.ita.escolaita.model.entity.Turma;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import static br.ita.escolaita.util.EscolaItaUtil.isBlankOrNull;

@Stateless
public class TurmaEjbBean implements TurmaEjbLocal {

    @PersistenceContext(unitName = "escolaIta-ejbPU")
    private EntityManager em;

    public void salvar(Turma turma) {
        em.persist(turma);
        em.flush();
    }

    public void alterar(Turma turma) {
        em.merge(turma);
        em.flush();
    }

    public List<Turma> listarTodas() {
        Query findAllQuery = em.createNamedQuery("turma.findAll");
        List<Turma> turmas = findAllQuery.getResultList();
        return turmas;
    }

    public List<Turma> listar(Turma t) {
        StringBuilder sql = new StringBuilder();
        StringBuilder where = new StringBuilder();
        sql.append("SELECT t FROM Turma t ");
        if (!isBlankOrNull(t.getNome())) {
            where.append("WHERE UPPER(t.nome) like UPPER('%").append(t.getNome()).append("%') ");
        }
        if (t.getSerie() != null){
            if (where.length() != 0){
                where.append("AND ");
            } else {
                where.append("WHERE ");
            }
            where.append("t.serie.id = ").append(t.getSerie().getId());
        }
        Query findAllQuery = em.createQuery(sql.append(where).toString());
        List<Turma> turmas = findAllQuery.getResultList();
        return turmas;
    }
}
